/**
 * @fileOverview mouseenter anchor begin add edge
 * @author huangtonger@aliyun.com
 */
const Page = require('../../base/');
const Global = require('../global');

Page.registerBehaviour('hoverAnchorActived', diagram => {
  const graph = diagram.getGraph();
  graph.behaviourOn('anchor:mouseenter', ev => {
    if (diagram.getSignal('panningItem') || diagram.getSignal('dragEdge')) {
      return;
    }
    const anchor = ev.shape;
    const item = anchor.getItem();
    const model = item.getModel();
    const tplModel = diagram.get('addEdgeModel');
    const addModel = {
      ...tplModel,
      source: model.id
    };
    const eventObj = {
      anchor: anchor.getPoint(),
      item
    };
    diagram.emit('hoveranchor:beforeaddedge', eventObj);
    if (eventObj.cancel) {
      diagram.css({
        cursor: Global.cursor.hoverUnEffectiveAnchor
      });
      return;
    }
    diagram.css({
      cursor: Global.cursor.hoverEffectiveAnchor
    });
    !anchor.get('destroyed') && anchor.setActived();
    diagram.beginAdd('edge', addModel);
    graph.draw();
  });
  graph.behaviourOn('anchor:mouseleave', ev => {
    if (!diagram.getSignal('dragEdge') && !diagram.getSignal('panningItem')) {
      const anchor = ev.shape;
      const item = anchor.getItem();
      diagram.css({
        cursor: Global.cursor.beforePanCanvas
      });

      if (!item.isSelected) {
        diagram.clearAnchor(item);
        diagram.setActived(item, false);
      }
      !anchor.get('destroyed') && anchor.clearActived();
      diagram.cancelAdd();
      graph.draw();
    }
  });
});
